﻿using Furion.CMS.Core;
using Furion.CMS.Domain;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.TaskScheduler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Furion.CMS.Application
{
    /// <summary>
    /// 任务监听器
    /// </summary>
    public class SpareTimeListener : ISpareTimeListener, ISingleton
    {
        private readonly IRepository<CrontabExecuteRecord> _recordRepository;

        public SpareTimeListener()
        {
            _recordRepository = App.GetService<IRepository<CrontabExecuteRecord>>();
        }

        private async Task UpdateExecuteRecordAsync(SpareTimer timer, string result, bool success = false)
        {
            // 拆解参数
            var args = timer.Description?.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries);
            if (args?.Length == 2)
            {
                var jobId = args[0].ToTryGuid();
                int.TryParse(args[1], out var jobRecordId);

                // 取最新的一条进行更新
                var lastRecord = _recordRepository.AsQueryable(false)
                    .FirstOrDefault(t => t.TaskId == jobId && t.Id == jobRecordId);
                if (lastRecord != null)
                {
                    lastRecord.Success = success;
                    lastRecord.Result = result;
                    lastRecord.UpdatedTime = DateTime.Now;
                    await _recordRepository.UpdateNowAsync(lastRecord);
                }
            }
        }

        public async Task OnListener(SpareTimerExecuter executer)
        {
            switch (executer.Status)
            {
                // 执行开始通知
                case 0:
                    Console.WriteLine($"{executer.Timer.WorkerName} 任务开始通知");
                    break;
                // 任务执行之前通知
                case 1:
                    Console.WriteLine($"{executer.Timer.WorkerName} 执行之前通知");
                    //await UpdateExecuteRecordAsync(executer.Timer, "运行中");
                    break;
                // 执行成功通知
                case 2:
                    Console.WriteLine($"{executer.Timer.WorkerName} 执行成功通知");
                    //await UpdateExecuteRecordAsync(executer.Timer, $"执行成功", true);
                    break;
                // 任务执行失败通知
                case 3:
                    Console.WriteLine($"{executer.Timer.WorkerName} 执行失败通知");
                    //await UpdateExecuteRecordAsync(executer.Timer, $"执行失败，错误:{executer.Timer.Exception.Values.FirstOrDefault().Message}");
                    break;
                // 任务执行停止通知
                case -1:
                    Console.WriteLine($"{executer.Timer.WorkerName} 执行停止通知");
                    break;
                // 任务执行取消通知
                case -2:
                    Console.WriteLine($"{executer.Timer.WorkerName} 执行取消通知");
                    //await UpdateExecuteRecordAsync(executer.Timer, "已被取消");
                    break;
                default:
                    break;
            }

            await Task.CompletedTask;
        }
    }
}
